//
//  JMAcademSearchViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/9/7.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMAcademSearchViewController.h"
#import "JMAcademyViewMode.h"
#import "JMAcademyCell.h"

#import "JMAcademInfoViewController.h"


@interface JMAcademSearchViewController ()<UITableViewDataSource,UITableViewDelegate>{

    int  lastId;
}

@property (nonatomic, strong) UISearchBar *serachBar;

@property (nonatomic, strong) UIButton *determineBtn;

@property (nonatomic, strong) UIImageView *lineImageView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) NSMutableArray *dataArray;


@end

@implementation JMAcademSearchViewController

- (UIButton *)determineBtn
{
    if (!_determineBtn) {
        UIButton *button = [[UIButton alloc]init];
        [button setTitle:@"确定" forState:UIControlStateNormal];
        [button setTitleColor:UIColorFromRGB(0xeb6100) forState:UIControlStateNormal];
        [button addTarget:self action:@selector(determineButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:14.0];
        button.frame = CGRectMake(UI_SCREEN_WITH - 44, 0, 44, 44);
        [self.view addSubview:_determineBtn = button];
    }
    return _determineBtn;
}

- (UIImageView *)lineImageView
{
    if (!_lineImageView) {
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"projectImage.bundle/line_image"];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        _lineImageView = imageView;
    }
    return _lineImageView;
}


- (UISearchBar *)serachBar
{
    if (!_serachBar) {
        _serachBar = [[UISearchBar alloc]initWithFrame:CGRectMake(70 , 0, UI_SCREEN_WITH -140, self.navigationItem.titleView.frame.size.height)];
        _serachBar.placeholder =@"搜索你感兴趣的大学";
    }
    return _serachBar;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, UI_SCREEN_WITH, UI_SCREEN_HEIGHT- 64)];
        _bottomView.backgroundColor = [UIColor clearColor];
        
        UILabel *la = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, UI_SCREEN_WITH - 150, 30)];
        la.backgroundColor = [UIColor clearColor];
        la.text = @"热门搜索";
        la.textColor = UIColorFromRGB(0x9b9999);
        la.font = [UIFont systemFontOfSize:16];
        [_bottomView addSubview:la];
        self.lineImageView.frame = CGRectMake(10, 40, UI_SCREEN_WITH - 20, 1);
        [_bottomView addSubview:self.lineImageView];
        
        NSArray *array = @[@"山东大学",@"清华大学",@"首都师范大学",@"北京大学",@"上海交通大学",@"山西大学",@"北京外国语学院",@"北京林业大学"];
        CGFloat with = (UI_SCREEN_WITH - (UI_SCREEN_WITH *0.0625 *3))/3.0;
        
        for(int i = 0;i <array.count;i++){
            UILabel *la = [[UILabel alloc]initWithFrame:CGRectMake(UI_SCREEN_WITH *0.0625 + (with + UI_SCREEN_WITH *0.03125) * (i%3), self.lineImageView.frameBottom + 10 + (25 + 10) *(i/3), with , 25)];
            la.backgroundColor = [UIColor clearColor];
            la.textColor = UIColorFromRGB(0x969696);
            la.text = array[i];
            la.textAlignment = NSTextAlignmentCenter;
            la.layer.masksToBounds =YES;
            la.font = [UIFont systemFontOfSize:12];
            la.layer.cornerRadius = 5.0;
            la.layer.borderWidth =0.5;
            la.layer.borderColor = [UIColorFromRGB(0xc4c4c4) CGColor];
            [_bottomView addSubview:la];
        }
    }
    return _bottomView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataArray;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, UI_SCREEN_WITH, UI_SCREEN_HEIGHT) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.backBtn.hidden = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:self.determineBtn];
    self.navigationItem.rightBarButtonItem =item;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.navigationItem.titleView.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = self.serachBar;
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    self.tableView.hidden =YES;
    [self setupRefresh];
}
#pragma mark 上下拉刷新数据
- (void)setupRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}

-(void)headerRereshing{
    lastId = 0;
    [self determineButtonClick:nil];
}
-(void)footerRereshing{
    [self determineButtonClick:nil];
}
#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * str=@"IDWW";
    JMAcademyCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    if(!cell){
        cell = [[JMAcademyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    JMCollegesMode *mode = [self.dataArray objectAtIndex:indexPath.row];
    [cell upCellInfoWith:mode];
    [cell.attentionBtn addTarget:self action:@selector(attentionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionBtn.tag = indexPath.row;
    if([mode.attention isEqualToString:@"1"]){
        cell.attentionBtn.type = @"1";
        [cell.attentionBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cell.attentionBtn setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image"] forState:UIControlStateNormal];
        [cell.attentionBtn setTitleColor:UIColorFromRGB(0xeb6100) forState:UIControlStateNormal];
    }else{
        cell.attentionBtn.type = @"0";
        [cell.attentionBtn setTitle:@"关注" forState:UIControlStateNormal];
        [cell.attentionBtn setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image_n"] forState:UIControlStateNormal];
        [cell.attentionBtn setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    JMAcademInfoViewController *vc = [JMAcademInfoViewController new];
    vc.mode = self.dataArray[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UI_SCREEN_WITH *0.234375;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}


-(void)determineButtonClick:(UIButton *)sender{
    lastId= 0;
    [JMTools showAlertView:self.view];
    if([self.serachBar.text isEqualToString:@""]){
        [JMTools showAlertView:self.view message:@"你没有输入要搜索的内容"];
        return;
    }
    
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:[NSString stringWithFormat:@"%d",lastId] forKey:@"last"];
        [dict setObject:@"15" forKey:@"size"];
        [dict setObject:self.serachBar.text forKeyedSubscript:@"keyword"];
        
        DDLOG(@"%@",dict);
        [JMAcademyViewMode fetchAcademyMessageParametes:dict block:^(id data, NSError *error, id currData) {
            [JMTools hiddenAlerView:self.view];
            if([data[@"status"] integerValue] == 1){
                [self.dataArray removeAllObjects];
                [self.dataArray  addObjectsFromArray:currData];
                self.bottomView.hidden= YES;
                self.tableView.hidden =NO;
                [self.tableView reloadData];
                [JMTools showAlertView:self.view message:data[@"message"]];
                [self.serachBar resignFirstResponder];
            }else{
                [JMTools showAlertView:self.view message:data[@"message"]];
            }
            [self.tableView.footer endRefreshing];
            [self.tableView.header endRefreshing];
        }];
    }
}

#pragma mark  guan zhu qu xiao
-(void)attentionButtonClick:(JMAttenButton *)sender{
    JMCollegesMode *mode = [self.dataArray objectAtIndex:sender.tag];
    
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if([sender.type isEqualToString:@"0"]){
        if(cf.user){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [dict setObject:[NSString stringWithFormat:@"%d",mode.collegeId] forKey:@"zhaosheng"];
            [JMAppNetworkClient addSchool_AttentionWithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                    [sender setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
                    [sender setTitle:@"取消" forState:UIControlStateNormal];
                    [sender setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image"] forState:UIControlStateNormal];
                    [JMTools showAlertView:self.view message:data[@"message"]];
                    sender.type =@"1";
                    mode.attention = @"1";
                    [self.dataArray replaceObjectAtIndex:sender.tag withObject:mode];
                }else{
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
                [JMTools hiddenAlerView:self.view];
            }];
        }
    }else{
        if(cf.user){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:0];
            [dict setObject:cf.user.userId forKey:@"user"];
            [dict setObject:cf.user.token forKey:@"token"];
            [dict setObject:[NSString stringWithFormat:@"%d",mode.collegeId] forKey:@"zhaosheng"];
            [JMAppNetworkClient cancleSchool_AttentionWithInfo:dict complete:^(id data, NSError *error) {
                if([data[@"status"] integerValue] == 1){
                    [JMTools showAlertView:self.view message:data[@"message"]];
                    [sender setTitleColor:UIColorFromRGB(0xa6a6a6) forState:UIControlStateNormal];
                    [sender setTitle:@"关注" forState:UIControlStateNormal];
                    [sender setImage:[UIImage imageNamed:@"projectImage.bundle/guanzhu_image_n"] forState:UIControlStateNormal];
                    sender.type =@"0";
                    mode.attention = @"0";
                    [self.dataArray replaceObjectAtIndex:sender.tag withObject:mode];
                }else{
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
                [JMTools hiddenAlerView:self.view];
                
            }];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
